<?php
namespace Modules\Skinov\Services;

use Modules\Skinov\Models\UserModel;

class UserService {
  public function encryptToken(array $payload) {
    return \Phalcon\Di::getDefault() -> getShared('crypt') -> encryptBase64(json_encode($payload), null, true);
  }

  public function decryptToken($token) {
    return json_decode(\Phalcon\Di::getDefault() -> getShared('crypt') -> decryptBase64($token, null, true), true);
  }

  public function create($data) {
    while(true) {
      $res = $this -> findFirstByAccount($data['account']);
      if($res['code'] !== 0) {
        break;
      } else {
        $data['account'] = rand(10000000, 99999999);
      }
    }

    $data['pid'] = intval($data['pid']);
    if($data['pid'] > 0) {
      $resPUser = $this -> findFirstById($data['pid']);
      if($resPUser['code'] !== 0) { $data['pid'] = 0; }
    }

    $model = new UserModel($data);
    if(!$model -> create()) {
      $messages = $model -> getMessages();
      return ['code' => -1, 'msg' => $messages[0] -> getMessage()];
    }

    return ['code' => 0, 'model'=>$model];
  }

  public function findFirstByAccount($account) {
    return $this -> findFirst(['conditions'=>'account = "' . $account . '"']);
  }

  public function findFirstById($id) {
    return $this -> findFirst(['conditions'=>'id = ' . $id . '']);
  }

  public function findFirst($parameters = []) {
    $model = UserModel::findFirst($parameters);
    if(!$model) { return ['code' => -1, 'msg' => '数据不存在或已删除']; }

    return ['code' => 0, 'model'=>$model];
  }
}
